/* eslint-disable array-bracket-spacing */
/* eslint-disable no-dupe-class-members */
/* eslint-disable indent */
'use strict'

const Service = require('egg').Service
const dayjs = require('dayjs')

// 信息要返回的字段
const attributes = ['id', 'name', 'pid', 'conf', 'status', 'isuse']

class DesktopcfgService extends Service {

    // 查询所有列表
    async getDesktopcfgList(params) {
        const { model, helper } = this.ctx
        const currentPage = params?.pageIndex ?? 1
        const pageSize = params?.pageSize ?? 50
        const { Op } = require('sequelize')
        const where = {}
        if (params.name) {
            where.name = {
                [Op.like]: `%${params.name}%`
            }
        }
        if (params.status !== undefined && params.status != null) {
            where.status = params.status
        }
        if (params.pid !== undefined && params.pid != null) {
            where.pid = params.pid
        }

        return await model.Desktopcfg.findAndCountAll({
            where,
            offset: (currentPage - 1) * pageSize, // 计算分页偏移量
            limit: pageSize,
            attributes,
            include: [
                {
                    model: model.Place,
                    // as: 'place',
                    attributes: ['barname', 'barcode']
                }
            ]
        })
            .then(async result => {
                if (result) {
                    return {
                        list: result.rows,
                        total: result.count
                    }
                }
                helper.failed(1008, null, '查询桌面配置列表失败')
                return false
            })
            .catch(async error => {
                helper.failed(1001, null, error.errors[0]?.message)
                return false
            })
    }

    // 新增桌面配置
    async createDesktopcfg(params) {
        const { model, helper } = this.ctx
        const { name, pid, conf, status } = params

        return await model.Desktopcfg.create({
            name,
            pid,
            conf,
            status,
            created_at: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss')
        })
            .then(async data => {
                if (data) {
                    return data
                }
                helper.failed(1005, null, '新增桌面配置失败')
                return false
            })
            .catch(async error => {
                helper.failed(1001, null, error.errors[0]?.message)
                return false
            })
    }

    // 编辑桌面配置
    async editDesktopcfg(params) {
        const { model, helper } = this.ctx

        return await model.Desktopcfg.findByPk(params.id)
            .then(async result => {
                if (result) {
                    delete params.id
                    return await result.update(params)
                        .then(async data => {
                            if (data) {
                                return data
                            }
                            helper.failed(1006, null, '编辑桌面配置失败')
                            return false
                        })
                        .catch(async error => {
                            helper.failed(1001, null, error.errors[0]?.message)
                            return false
                        })
                }
                helper.failed(1004, null, '桌面配置不存在')
                return false
            })
            .catch(async error => {
                helper.failed(1001, null, error.errors[0]?.message)
                return false
            })
    }

    // 删除桌面配置
    async deleteDesktopcfg(params) {
        const { model, helper } = this.ctx

        return await model.Desktopcfg.findByPk(params.id)
            .then(async result => {
                if (result) {
                    return await result.destroy()
                        .then(async data => {
                            if (data) {
                                return data
                            }
                            helper.failed(1007, null, '删除桌面配置失败')
                            return false
                        })
                        .catch(async error => {
                            helper.failed(1001, null, error.errors[0]?.message)
                            return false
                        })
                }
                helper.failed(1004, null, '桌面配置不存在')
                return false
            })
            .catch(async error => {
                helper.failed(1001, null, error.errors[0]?.message)
                return false
            })
    }

    // 应用门店桌面配置
    async applyDesktopcfg(params) {
        const { model, helper } = this.ctx
        // 使用事务
        const t = await model.transaction()

        try {
            const result = await model.Desktopcfg.findOne({
                where: {
                    id: params.id
                },
                transaction: t,
                attributes,
                include: [
                    {
                        model: model.Place,
                        as: 'place',
                        attributes: ['barname', 'barcode']
                    }
                ]
            })
            if (!result) {
                await t.commit()
                helper.failed(1004, null, '桌面配置不存在')
                return false
            }

            // 将所有isuse设置false
            await model.Desktopcfg.update({
                isuse: 0
            }, {
                where: {
                    pid: params.pid
                },
                transaction: t
            })

            await result.update({
                isuse: 1
            }, {
                transaction: t
            })
            await t.commit()
            return result
        } catch (error) {
            await t.rollback() // 回滚
            helper.failed(1001, null, error.errors[0]?.message)
            return false
        }
    }


    // 请求门店当前使用的配置
    async getCurrentDesktopcfg(params) {
        const { model, helper } = this.ctx
        const { pid } = params

        const where = {
            pid,
            isuse: 1
        }
        return await model.Desktopcfg.findOne({
            where,
            attributes,
            include: [
                {
                    model: model.Place,
                    as: 'place',
                    attributes: ['barname', 'barcode']
                }
            ]
        })
            .then(async result => {
                if (result) {
                    if (result.status === 1) {
                        return result
                    }
                    helper.failed(2002, null, '门店配置已停用')
                    return false
                }
                helper.failed(1002, null, '门店配置信息错误')
                return false
            })
            .catch(async error => {
                helper.failed(1001, null, error.errors[0]?.message)
                return false
            })
    }
}

module.exports = DesktopcfgService
